package com.kl.forum.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kl.forum.dao.CircleArticleMapper;
import com.kl.forum.dao.CircleDicMapper;
import com.kl.forum.dao.UserCircleMapper;
import com.kl.forum.entity.CircleDic;
import com.kl.forum.entity.UserCircle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CircleDicService {

    @Autowired
    private CircleDicMapper circleDicMapper;

    @Autowired
    private UserCircleMapper userCircleMapper;

    @Autowired
    private CircleArticleMapper  circleArticleMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public List<Map> findCircle(){
      return   circleDicMapper.findCircle();
    }

    public CircleDic findCircleOne(Integer circleId,Integer userId) {
        Map map =new HashMap();
        map.put("circleId",circleId);
        CircleDic circleDic=circleDicMapper.findCircleOne(map);
        //帖子数量  关注数量 统计    阅读量+1
        int articleNum= circleArticleMapper.countByCircleId(circleDic.getId());
        circleDic.setArticleNum(articleNum);
        int followNum= userCircleMapper.countByCircleId(circleDic.getId());
        circleDic.setFollowNum(followNum);
        UserCircle userCircle= userCircleMapper.findOneCircleUser(circleDic.getId(),userId);
       if (userCircle!=null){
           circleDic.setStatus(userCircle.getStatus());
       }
        if (!stringRedisTemplate.opsForHash().hasKey("circleViewNumCount",String.valueOf(circleDic.getId()))){
            stringRedisTemplate.opsForHash().put("circleViewNumCount",String.valueOf(circleDic.getId()),"1");
        }else {
            stringRedisTemplate.opsForHash().increment("circleViewNumCount",String.valueOf(circleDic.getId()),1);
        }
        circleDic.setViewNum(Integer.valueOf((String) stringRedisTemplate.opsForHash().get("circleViewNumCount",String.valueOf(circleDic.getId()))));
        return circleDic;
    }

    public PageInfo findMyCircle(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String,Object> map=new HashMap<>();
        map.put("userId",userId);
        List<Map> list=circleDicMapper.findMyCircle(map);
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    public int update(CircleDic circleDic){
        return  circleDicMapper.updateByPrimaryKeySelective(circleDic);
    }
}
